from sklearn.datasets import load_boston

# 导入波斯顿的房价数据
boston = load_boston()


from sklearn.cross_validation import train_test_split
import numpy as np

# 提取出训练、测试集及目标值
X = boston.data
y = boston.target
# print(X)

# 随机采样25%的数据构建测试样本，其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=33, test_size=0.25)

# 分析回归目标值的差异
# print('目标值最大值：',np.max(y))
# print('目标值最小值:',np.min(y))
# print('目标平均值:',np.mean(y))


#  从sklearn.preprocessing导入数据标准化模块
from sklearn.preprocessing import StandardScaler

# 分别初始化对特征和目标值的标准化模块
ss_X = StandardScaler()
ss_y= StandardScaler()

# 分别对训练和测试数据的特征以及目标值进行标准化处理
X_train = ss_X.fit_transform(X_train)
X_test = ss_X.fit_transform(X_test)
# y_train = ss_y.fit_transform(y_train)
# y_test = ss_y.transform(y_test)
y_train = ss_y.fit_transform(y_train.reshape(-1, 1))
y_test = ss_y.transform(y_test.reshape(-1, 1))


# sklearn.neighbors导入KNeighborsRegressor(k近邻回归器)
from sklearn.neighbors import KNeighborsRegressor

# 初始化K近邻回归器，并且调整配置，是的预测的方式为平均回归：weights='uniform'
uni_knr = KNeighborsRegressor(weights='uniform')
uni_knr.fit(X_train, y_train)
uni_knr_y_predict = uni_knr.predict(X_test)
# print(uni_knr_y_predict)


# 初始化K近邻回归器，并且调整配置，使得预测的方式为根据距离加权回归：weights='distance'
dis_knr = KNeighborsRegressor(weights='distance')
dis_knr.fit(X_train, y_train)
dis_knr_y_predict = uni_knr.predict(X_test)
# print(dis_knr_y_predict)



from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
# 使用R-squared、MSE、MAE三种指标对平均回归配置的K近邻模型在测试集上进行性能评估
print('R-squared value of uniform-weighted KNeighborsRegressor:',uni_knr.score(X_test, y_test))
print('The mean squared error of uniform-weighted KNeighborsRegressor:', mean_squared_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(uni_knr_y_predict)))
print('The mean absolute error of uniform-weighted KNeighborsRegressor:', mean_absolute_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(uni_knr_y_predict)))


# 使用R-squared、MSE、MAE三种指标对根据距离加权回归配置的K近邻模型在测试集上进行性能评估
print('R-squared value of distance-weighted KNeighborsRegressor:',dis_knr.score(X_test, y_test))
print('The mean squared error of distance-weighted KNeighborsRegressor:', mean_squared_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(dis_knr_y_predict)))
print('The mean absolute error of distance-weighted KNeighborsRegressor:', mean_absolute_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(dis_knr_y_predict)))


